package org.smile.db.sql.page;

import java.sql.SQLException;

import org.smile.util.RegExp;

public class SQL2000DialectPage implements DialectPage {

	private String newSql;
	
	private String orderby;
	
	public SQL2000DialectPage(String sql) throws SQLException{
		/**
		 * 查的order by 
		 */
		RegExp reg=new RegExp(" order +by ",false); 
		
		int indexEnd=reg.lastIndexEnd(sql);
		
		//最后匹配的结束
		int indexStart=reg.lastIndex(sql);
		//处理后的sql
		newSql=sql;
		if(indexEnd>0){
			orderby=sql.substring(indexEnd,sql.length());
			newSql=sql.substring(0,indexStart);
		}
		if(orderby==null){
			throw new SQLException("请指定排序列名称");
		}
		
	}
	public String getCountSql() {
		//条数sql
		return "SELECT COUNT(*) FROM ("+newSql+") COUNT_TABLE_T";
	}
	
	public String getDataSql(int page,int size) {
		int firstRow=(page-1)*size;
		int endRow=firstRow+size;
		StringBuffer middleOrderby=new StringBuffer();
		String[] orderbys=orderby.split(",");
		for(int i=0;i<orderbys.length;i++){
			RegExp descReg=new RegExp(" desc *$",false);
			RegExp ascReg=new RegExp(" asc *$",false);
			String[] str=descReg.find(orderbys[i]);
			if(str!=null){
				middleOrderby.append(descReg.replaceAll(orderbys[i], ""));
			}else{
				str=ascReg.find(orderbys[i]);
				if(str!=null){
					middleOrderby.append(ascReg.replaceAll(orderbys[i], " DESC "));
				}else{
					middleOrderby.append(orderbys[i] +" DESC ");
				}
			}
			if(i<orderbys.length-1){
				middleOrderby.append(",");
			}
		}
		RegExp selectReg=new RegExp("select",false);
		int index=selectReg.firstIndexEnd(newSql);
		//数据sql
		StringBuffer sql=new StringBuffer();
		sql.append("SELECT * FROM (SELECT TOP "+size+" * FROM (");
		sql.append(newSql.substring(0,index)).append(" TOP "+endRow);
		sql.append(newSql.substring(index)).append(" ORDER BY "+ orderby +") T ORDER BY "+middleOrderby+") T ORDER BY "+ orderby);
		return sql.toString();
	}

}
